/*
** team.c for  in /home/faye_m//zappy
** 
** Made by mouhamed faye
** Login   <faye_m@epitech.net>
** 
** Started on  Wed Jun 22 20:49:36 2011 mouhamed faye
** Last update Fri Jul  1 16:47:34 2011 mouhamed faye
*/
#include <stdio.h>
#include <stdlib.h>
#include "team.h"
#include "server.h"
#include "player.h"
Class_team	*add_team(Class_team *req, char *team, int max_player)
{
  Class_team *list_of_team; 
  list_of_team = malloc(10 * sizeof(Class_team)); //10 = nb team
  if(list_of_team ==  NULL)
    printf ("fonction add_command segfault segfault the zappy ....\n");
  list_of_team->team_name = team;
  list_of_team->nb_player += 1 ;//get_cmd_delay function
  list_of_team->max_player = max_player;
  list_of_team->max_req += 1;
  list_of_team->next = NULL;
  if (req == NULL)
    return (list_of_team);
  else
    {
      Class_team	*tmp = req; 
      while (tmp->next != NULL)
	{
	  tmp = tmp->next;
	}
      tmp->next = list_of_team;
      return(req);
    }
}

int	cmd_add_player(Vars_Packages *var)
{ 
  Class_team	*tmp = malloc(sizeof(*tmp));
   tmp = var->list_of_team;
  while (tmp->next != NULL)
    {	
      if (strcmp(tmp->team_name, var->buffer) == 0)
	{
	  tmp->list_player = add_player(tmp->list_player, var->sockfd2);
	  printf ("\tSending OK to ...... %d\n", var->sockfd2);
	  // write(var->sockfd2, "OK\n", 3);
	  return 1;
	}
      tmp = tmp->next;
      }
  printf ("\tSending KO to ...... %d\n", var->sockfd2);
  //  write(var->sockfd2, "KO\n", 3);
  // disconnect(var); wait to disconnect : test if nb_req = 1
  return(0);
}

void	show_player(Vars_Packages *var)
{
  Class_team	*tmp = malloc(sizeof(*tmp));
  tmp = var->list_of_team;

  while (tmp->next != NULL)
    {	
      printf ("team : %s\n", tmp->team_name);
      while(tmp->list_player != NULL)
	{
	  printf ("Joueur:  %d\n", tmp->list_player->num_joueur);
	  tmp->list_player = tmp->list_player->next;
	}
      tmp = tmp->next;
    }
}


int	cmd_add_request(Vars_Packages *var)
{
   show_player(var);
}

void   cmd_analyzer(Vars_Packages *var)
{
  if (cmd_add_player(var))//go to a team
    printf ("MAP: sending Positon %d\n", var->sockfd2, var->buffer);
  else if (cmd_add_request(var))// ask for request
    printf ("Send ok func on team \n");
  else
     printf ("Bad request \n");
}

Class_team	*del_player(Class_team *req, int  socket)
{
  if (req == NULL)
    return NULL;
  
  if (req != NULL)
    {
      Class_team *to_return =  req->next;
      free(req);
      return (to_return);
    }
  else
    {
      return (NULL);
    }
}
/**********************fonction affichage  team et joueur *********/
void	display_team(Class_team *all_team, int max)
{
  Class_team *tmp = all_team;
  int	i;
  i =	0;
  printf ("Teams :\n");
  while (tmp->next != NULL)
    {
      printf ("\tName(%s)   Max(%d)\n", tmp->team_name, max);
      tmp = tmp->next;
    }
}
